package com.zff.rental.tools;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.Date;
import java.util.Objects;

/**
 * @author HCY
 */
public final class JwtTools {
    private static final String ENCODE_SECRET_KEY = "XX#$%()(#*!()!KL<><MQLMNQNQJQKsdfkjsdrow32234545fdf>?N<:{LWPW";

    /**
     * 请求头中Token的key
     */
    private static final String REQUEST_HEADER_AUTHORIZATION = "token";


    /**
     * 生成token
     */
    public static String createToken(Long userId, boolean admin, long expireTime) {
        Date date = new Date(System.currentTimeMillis() + expireTime);

        Algorithm algorithm = Algorithm.HMAC256(ENCODE_SECRET_KEY);
        return JWT.create()
                .withExpiresAt(date)
                // 管理员
                .withClaim("admin", admin)
                // 用户Id
                .withClaim("userId", userId)
                .sign(algorithm);
    }

    /**
     * 校验token是否失效
     */
    public static boolean checkToken(String token) {
        Algorithm algorithm = Algorithm.HMAC256(ENCODE_SECRET_KEY);
        JWTVerifier verifier = JWT.require(algorithm).build();
        try {
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            return false;
        }
    }

    /**
     * 获取用户account
     */
    public static Long getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asLong();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获取用户account
     */
    public static boolean isAdmin(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            Boolean admin = jwt.getClaim("admin").asBoolean();
            return Objects.requireNonNullElse(admin, false);
        } catch (JWTDecodeException e) {
            return false;
        }
    }

    public static String getRequestHeaderAuthorization() {
        return REQUEST_HEADER_AUTHORIZATION;
    }

    /**
     * 获取请求头的Token
     */
    public static String getTokenByServletRequest(HttpServletRequest request) {
        String token = request.getHeader(getRequestHeaderAuthorization());
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring("Bearer ".length());
        }
        return token;
    }

    public static void addTokenToHttpServletResponse(HttpServletResponse response, String token) {
        response.addHeader(JwtTools.getRequestHeaderAuthorization(), token);
    }
}